package jmm.happensbefore;

/**
 * @author lizhichuan
 * @date 2024/3/21 11:44
 */
public class VolatileExample02 {
    int x = 0;
    boolean v = false;
    public void writer(){
        x = 42;
        v = true;
    }

    public void reader(){
        if(v == true){
            //x的值是多少呢？
            System.out.println(x);
        }
    }

    public static void main(String[] args) {
        VolatileExample02 volatileExample02 = new VolatileExample02();
        while (true){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    volatileExample02.reader();
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    volatileExample02.writer();
                }
            }).start();
        }

    }

}
